import random

from django.views import View
from django.contrib import auth
from io import StringIO, BytesIO
from PIL import Image, ImageDraw, ImageFont
from django.shortcuts import render, HttpResponse, reverse, redirect, Http404
from django.http import JsonResponse
from app01.vailds import get_vaild_num, vaild_random, paginators
from app01.models import *
from django.core.paginator import Paginator
from django.db.models import Count
from django.db.models.functions import TruncMonth


# Create your views here.


def login(request):
    return render(request, "bbs/login.html")


class Login(View):
    def get(self, request):
        return render(request, "bbs/login.html")

    def post(self, request):
        msg = {"status": 100, "msg": "", "url": reverse('index')}
        username = request.POST.get("username")
        pwd = request.POST.get("pwd")
        print(request.POST)
        vaild_check = request.POST.get("vaild_check")
        user = auth.authenticate(request, username=username, password=pwd)
        if request.session["vaild_num"].lower() == vaild_check.lower():
            if user:
                request.session.flush()
                auth.login(request, user)
                msg["msg"] = "登陆成功"
            else:
                msg["msg"] = "用户或密码不对"
        else:
            msg["msg"] = "验证码不对"
        return JsonResponse(msg)


def valid_check(request):
    img = Image.new("RGB", (320, 33), vaild_random(3))
    draw = ImageDraw.Draw(img, "RGB")
    font = ImageFont.truetype("static/font/fzht.TTF", size=25)
    # xy: x横轴 y竖轴,text：文本内容,fill=None： 字体颜色 ,font=None：要用哪种字体
    vaild_num = get_vaild_num(6)
    draw.text((120, 6), vaild_num, fill=vaild_random(3), font=font)

    width = 270
    height = 40
    for i in range(10):
        x1 = random.randint(0, width)
        x2 = random.randint(0, width)
        y1 = random.randint(0, height)
        y2 = random.randint(0, height)
        draw.line((x1, x2, y1, y2), fill=vaild_random(3))

    for i in range(50):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=vaild_random(3))
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=vaild_random(3))

    """
        生成随机字符串xxx，存入session表中，在cookie中写入sessionid=xxx
    """
    request.session["vaild_num"] = vaild_num
    io = BytesIO()
    img.save(io, "png")  # 直接通过二进制形式写到内存中
    data = io.getvalue()  # 获取到数据给它返回
    return HttpResponse(data)


class Register(View):
    def get(self, request):
        return render(request, "bbs/register.html")

    def post(self, request):
        msg = {"status": 100, "msg": "", "url": reverse('index')}
        username = request.POST.get("username")
        pwd = request.POST.get("pwd")
        email = request.POST.get("email")
        phone = request.POST.get("phone")
        avatar = request.FILES.get("avatar")
        # with open("upload/{}11".format(avatar.name), "wb") as f:
        #     # from django.core.files.base import File
        #     for line in avatar.chunks():
        #         f.write(line)

        if all([username, pwd, email, phone]):
            if not UserInfo.objects.filter(username=username).first():
                user = UserInfo.objects.create_user(username=username,
                                                    password=pwd,
                                                    email=email,
                                                    phone=phone,
                                                    avatar=avatar)
                msg["msg"] = "注册成功"
            else:
                msg["msg"] = "注册失败，用户已存在"
        else:
            msg["msg"] = "选项不能为空"
        return JsonResponse(msg)


def index(request, page=1):
    articles = Article.objects.all()
    articles, per_list, page = paginators(articles, page)
    return render(request, 'bbs/index.html', locals())


def logout(request):
    auth.logout(request)
    return redirect(reverse("index"))


def user_site(request, name, *args, **kwargs):
    # user = UserInfo.objects.filter(username=name).first()
    user = Blog.objects.filter(userinfo__username=name).first()
    if not user:
        return render(request, "bbs/error.html")

    # 用户文章分类
    page = request.GET.get("page")
    article = Article.objects.filter(blog__userinfo__username=name).all()

    # 标签, 按用户查找出标签， 然后获取文章的总数，以元组方式列出，最后在排序
    category_list = Category.objects.filter(blog__userinfo__username=name).annotate(count=Count("article__title")). \
        values_list("id", "name", "count").order_by("-count")

    # 分类
    tag_list = Tag.objects.filter(blog__userinfo__username=name).annotate(count=Count("article__title")). \
        values_list("id", "name", "count").order_by("-count")

    # 按时间分类  先按用户找出文章， 分割时间之后列出，然后在将时间分组，最后在做成一个列表返回
    archvie_date_list = article.annotate(t_m=TruncMonth("create_time")).values("t_m").annotate(
        count_tm=Count("t_m")).values_list("t_m", "count_tm")

    # 标签
    category_id = kwargs.get("category_id")
    if kwargs.get("category_id"): article = article.filter(category__id=category_id)

    # 分类
    tag_id = kwargs.get("tag_id")
    if kwargs.get("tag_id"): article = article.filter(tag__id=tag_id)

    # 文章分类
    archive_id = kwargs.get("archive_id")
    if archive_id:
        y_m = archive_id.split("-")
        article = article.filter(create_time__year=y_m[0], create_time__month=y_m[1])

    articles, per_list, page = paginators(article, page)

    return render(request, "bbs/user_site.html", locals())


def archive_detail(request, name, archive_id):
    user = Blog.objects.filter(userinfo__username=name).first()
    if not user:
        return render(request, "bbs/error.html")

    x = user.article_set.filter(pk=archive_id)
    print(x)
    article = Article.objects.filter(pk=archive_id)
    return render(request, "bbs/archive_detail.html",
                  {"articles": article, "user": user})
